//分页参数设置 这些全局变量关系到分页的功能
var startAllAppoint = 1;
var limitAllAppoint = 10;
var currentPageAllAppoint = 1;
var totalPageAllAppoint = 0;
var dataLength = 0;
layui.config({
	base : "js/"
}).use(['form','layer','jquery','laypage'],function(){
	var form = layui.form(),
		layer = parent.layer === undefined ? layui.layer : parent.layer,
		laypage = layui.laypage,
		$ = layui.jquery;

	//加载页面数据
	getPageList();
	toPage();
	

	//查询
	$(".search_btn").click(function(){
		var userArray = [];
		if($(".search_input").val() != ''){
			var index = layer.msg('查询中，请稍候',{icon: 16,time:false,shade:0.8});
            setTimeout(function(){
            	startAllAppoint =1;
				currentPageAllAppoint =1;
				getPageList();
				toPage();
                layer.close(index);
            },2000);
		}else{
			layer.msg("请输入需要查询的内容");
		}
	})

	//添加会员
	$(".usersAdd_btn").click(function(){
		var index = layui.layer.open({
			title : "添加配送单",
			type : 2,
			content : "orderDeliveryAdd.html",
			success : function(layero, index){
				layui.layer.tips('点击此处返回供货商列表', '.layui-layer-setwin .layui-layer-close', {
					tips: 3
				});
			}
		})
		//改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
		$(window).resize(function(){
			layui.layer.full(index);
		})
		layui.layer.full(index);
	})

    //全选
	form.on('checkbox(allChoose)', function(data){
		var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
		child.each(function(index, item){
			item.checked = data.elem.checked;
		});
		form.render('checkbox');
	});

	//通过判断文章是否全部选中来确定全选按钮是否选中
	form.on("checkbox(choose)",function(data){
		var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
		var childChecked = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"]):checked')
		if(childChecked.length == child.length){
			$(data.elem).parents('table').find('thead input#allChoose').get(0).checked = true;
		}else{
			$(data.elem).parents('table').find('thead input#allChoose').get(0).checked = false;
		}
		form.render('checkbox');
	})

	//操作
	$("body").on("click",".toDelivery",function(){  //配送
		var _this = $(this);
		var dto = 
 		{
 			"id":_this.attr("data-id"),
 			"status":2
 		}
 		$.ajax({
			        url: API_URL_HEAD+"outPutBills/update",
			        type: 'post',
			        contentType: 'application/json; charset=utf-8',
			        data: JSON.stringify(dto),
			        dataType: 'json',
			        success: function (data) {
			        	if(data.code == 0){
		               //刷新父页面
			 			startAllAppoint =1;
						currentPageAllAppoint =1;
						getPageList();
						toPage();
	            		}
			        }
			   });
//			   var delIdArray = [];
//			   delIdArray.push(_this.attr("data-id"));
//			   var params = JSON.stringify(delIdArray)
//		window.open(API_URL_HEAD+"file/generateExcel/"+params);	   
		
	})
	//操作
	$("body").on("click",".toAudit",function(){  //审核
		var _this = $(this);
		var index = layui.layer.open({
			title : "审核配送单",
			type : 2,
			content : "orderDeliveryAuditDetail.html?objId="+_this.attr("data-id"),
			success : function(layero, index){
				$.ajax({
			        url: API_URL_HEAD+"outPutBills/detail/"+_this.attr("data-id"),
			        type: 'get',
			        async: false,
			        contentType: 'application/json; charset=utf-8',
			        dataType: 'json',
			        success: function (data) {
			        	var vo = data.data;
			        	$(".billSn", layero.find("iframe")[0].contentWindow.document).val(vo.billSn);
			        	$(".deliveryName", layero.find("iframe")[0].contentWindow.document).val(vo.deliveryName);
			        	$(".deliveryTel", layero.find("iframe")[0].contentWindow.document).val(vo.deliveryTel);
			 			$(".orderNums", layero.find("iframe")[0].contentWindow.document).val(vo.orderNums);
			 			$(".waterNums", layero.find("iframe")[0].contentWindow.document).val(vo.waterNums);
			 			$(".recycleBucketSum", layero.find("iframe")[0].contentWindow.document).val(vo.recycleBucketSum);
			 			$(".auditRemark", layero.find("iframe")[0].contentWindow.document).val(vo.auditRemark);
			        }
			   });
				layui.layer.tips('点击此处返回供货商列表', '.layui-layer-setwin .layui-layer-close', {
					tips: 3
				});
			}
		})
		//改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
		$(window).resize(function(){
			layui.layer.full(index);
		})
		layui.layer.full(index);
	})
	//操作
	$("body").on("click",".detail",function(){  //详情
		var _this = $(this);
		var index = layui.layer.open({
			title : "配送单详情",
			type : 2,
			content : "orderDeliveryDetail.html?objId="+_this.attr("data-id")+"&orderIds="+_this.attr("order-ids"),
			success : function(layero, index){
				
				layui.layer.tips('点击此处返回供货商列表', '.layui-layer-setwin .layui-layer-close', {
					tips: 3
				});
			}
		})
		//改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
		$(window).resize(function(){
			layui.layer.full(index);
		})
		layui.layer.full(index);
	})
	//操作
	$("body").on("click",".print",function(){  //打印
		var _this = $(this);
		var ids = "";
		ids+= _this.attr("data-id");
		window.open(API_URL_HEAD+"file/generateExcel?ids="+ids);
		
//		var ExcelSheet ;
//		var wb;
//		try {
//			ExcelSheet     = new ActiveXObject("Excel.Application");
//			wb = ExcelSheet.Workbooks.open("C:/Users/Administrator/Desktop/order.xls");
//			var objsheet =  wb.Worksheets("Sheet1");
//			ExcelSheet.DisplayAlerts=false;
//			ExcelSheet.Save();
//			// 使EXCEL窗口可见
//			ExcelSheet.Visible = true;
//			//if(ExcelSheet.Saved){
//				ExcelSheet.ActiveSheet.PrintPreview();
//				//ExcelSheet.WorkBooks.Close();
//				//ExcelSheet.Quit();
//			//}
//			//ActiveWindow.ExcelSheet.PrintOut("1", true,false);
//			//window.location="printZxd.action?id="+id;
//		}catch(e) {
//			if (ExcelSheet != undefined){
//				alert('错误 : ' + e);
//				ExcelSheet.Quit();
//				return '';
//			}
//			alert("请启用ActiveX控件设置!");
//			return '';
//		}
		
//		var url = API_URL_HEAD+'file/generateExcel?ids='+ids;
//		
//		   var xhr = new XMLHttpRequest();
//		
//		   xhr.open('GET', url, true);        // 也可以使用POST方式，根据接口
//		
//		   xhr.responseType = "blob";    // 返回类型blob
//		   
//		   xhr.setRequestHeader("ontent-type","application/json; charset=utf-8")
//		
//		   // 定义请求完成的处理函数，请求前也可以增加加载框/禁用下载按钮逻辑
//		
//		   xhr.onload = function () {
//		
//		       // 请求完成
//		
//		       if (this.status === 200) {
//		
//		           // 返回200
//		
//		           var blob = this.response;
//		
//		           var reader = new FileReader();
//		
//		           reader.readAsDataURL(blob);    // 转换为base64，可以直接放入a表情href
//		
//		           reader.onload = function (e) {
//		
//		               // 转换完成，创建一个a标签用于下载
//		
//		               var a = document.createElement('a');
//		
//		               a.download = 'data.xlsx';
//		
//		               a.href = e.target.result;
//		
//		               $("body").append(a);    // 修复firefox中无法触发click
//		
//		               a.click();
//		
//		               $(a).remove();
//		
//		           }
//		
//		       }
//		
//		   };
//		
//		   // 发送ajax请求
//		
//		   xhr.send()
	})

	$("body").on("click",".users_del",function(){  //删除
		var _this = $(this);
		layer.confirm('确定删除此用户？',{icon:3, title:'提示信息'},function(index){
			$.ajax({
			        url: API_URL_HEAD+"outPutBills/deleteById/"+_this.attr("data-id"),
			        type: 'get',
			        async: false,
			        contentType: 'application/json; charset=utf-8',
			        dataType: 'json',
			        success: function (data) {
			        	var vo = data.data;
						layer.close(index);
						startAllAppoint =1;
						currentPageAllAppoint =1;
						getPageList();
						toPage();
			        }
			  });
			layer.close(index);
		});
	})

	function renderData(data){
		var dataHtml = '';
		if(data.length != 0){
			for(var i=0;i<data.length;i++){
				var status = "";
				var ctrlHtml = "";
				var toDeliveryBtn  =  '<a class="layui-btn layui-btn-mini toDelivery" data-id="'+data[i].id+'"><i class="layui-icon-release"></i>配送</a>';
				var toAuditBtn =   '<a class="layui-btn layui-btn-danger layui-btn-mini toAudit" data-id="'+data[i].id+'"><i class="layui-icon-ok"></i>审核</a>';
				var detailBtn =   '<a class="layui-btn layui-btn-danger layui-btn-mini detail" data-id="'+data[i].id+'"  order-ids="'+data[i].orderIds+'"><i class="layui-icon-log"></i>详情</a>';
				var excelBtn = '<a class="layui-btn layui-btn-danger layui-btn-mini print" data-id="'+data[i].id+'" ><i class="layui-icon-log"></i>导出</a>';
				if(data[i].status == 1)
				{
					status = "生成";
					ctrlHtml += toDeliveryBtn+excelBtn;
				}
				else
				if(data[i].status == 2)
				{
					status = "配送中";
				}else
				{
					status = "完成";
				}
				var auditStatus = "";
				if(data[i].auditStatus ==1 )
				{
					auditStatus = "待审核";
				}
				else
				if(data[i].auditStatus ==2)
				{
					auditStatus = "审核通过";
				}else
				if(data[i].auditStatus ==3)
				{
					auditStatus = "审核失败";
				}
				if(data[i].status == 2 && data[i].auditStatus ==1)
				{
					ctrlHtml += toAuditBtn+excelBtn;
				}
				ctrlHtml += detailBtn;
				dataHtml += '<tr>'
//			    	+  '<td><input type="checkbox" name="checked" lay-skin="primary" lay-filter="choose"></td>'
			    	+  '<td>'+data[i].billSn+'</td>'
			    	+  '<td>'+data[i].deliveryName+'</td>'
			    	+  '<td>'+data[i].deliveryTel+'</td>'
			    	+  '<td>'+data[i].orderNums+'</td>'
			    	+  '<td>'+data[i].waterNums+'</td>'
			    	+  '<td>'+data[i].recycleBucketSum+'</td>'
			    	+  '<td>'+status+'</td>'
			    	+  '<td>'+auditStatus+'</td>'
//			    	+  '<td>'+data[i].auditRemark+'</td>'
//			    	+  '<td>'+data[i].remark+'</td>'
			    	+  '<td>'+convertUTCTimeToLocalTime(data[i].createTime)+'</td>'
			    	+  '<td>'+convertUTCTimeToLocalTime(data[i].modifyTime)+'</td>'
			    	+  '<td>'
					+  ctrlHtml
			        +  '</td>'
			    	+'</tr>';
			}
		}else{
			dataHtml = '<tr><td colspan="14">暂无数据</td></tr>';
		}
		$(".vo_content").html(dataHtml);
	}
	
	function getPageList(){
	var data={
		"searchKey":$(".search_input").val()
	};
	var pageData ={
		"page":startAllAppoint,
		"limit":limitAllAppoint
		
		};
		$.extend(data, pageData);
	    $.ajax({
        url: API_URL_HEAD+"outPutBills/queryPage",
        type: 'post',
        async: false,
        data :JSON.stringify(data),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (data) {
        	var list = data.data.list;
        	renderData(list);
        	startAllAppoint = data.data.pageNum;//当前页数(后台返回)
        	totalPageAllAppoint = data.data.pages;//总页数(后台返回)
        }
    });
}
	
     function toPage(){
    	var nums = 10;
    //调用分页
      laypage({
        cont: 'page'
        ,pages: totalPageAllAppoint //得到总页数
        ,curr: currentPageAllAppoint
        ,skip: true
        ,jump: function(obj, first){
            currentPageAllAppoint = obj.curr;
            startAllAppoint = obj.curr;
          if(!first){ //一定要加此判断，否则初始时会无限刷新
          	getPageList();//一定要把翻页的ajax请求放到这里，不然会请求两次。
               }
          	form.render();
            }
         });
};   
})

//格式化时间
function formatTime(_time){
    var year = _time.getFullYear();
    var month = _time.getMonth()+1<10 ? "0"+(_time.getMonth()+1) : _time.getMonth()+1;
    var day = _time.getDate()<10 ? "0"+_time.getDate() : _time.getDate();
    var hour = _time.getHours()<10 ? "0"+_time.getHours() : _time.getHours();
    var minute = _time.getMinutes()<10 ? "0"+_time.getMinutes() : _time.getMinutes();
    return year+"-"+month+"-"+day+" "+hour+":"+minute;
}
function convertUTCTimeToLocalTime(UTCDateString) {
        if(!UTCDateString){
          return '-';
        }
        function formatFunc(str) {    //格式化显示
          return str > 9 ? str : '0' + str
        }
        var date2 = new Date(UTCDateString);     //这步是关键
        var year = date2.getFullYear();
        var mon = formatFunc(date2.getMonth() + 1);
        var day = formatFunc(date2.getDate());
        var hour = formatFunc(date2.getHours());
        var second = formatFunc(date2.getSeconds());
//      var noon = hour >= 12 ? 'PM' : 'AM';
//      hour = hour>=12?hour-12:hour;
//      hour = formatFunc(hour);
        var min = formatFunc(date2.getMinutes());
        var dateStr = year+'-'+mon+'-'+day+' '+hour+':'+min+':'+second;
        return dateStr;
     } 